from peewee import *

db = MySQLDatabase('nemtocr', host='localhost', port=3800, user='root', password='!@mtg23YWZ^&')


class UniversityDetail(Model):
    id = PrimaryKeyField()
    year = IntegerField()
    code = CharField(max_length=32)
    name = CharField(max_length=64)
    history = TextField()
    special_major = TextField()
    change_rule = TextField()
    wan_plan = TextField()
    introduction_1 = TextField()
    introduction_2 = TextField()
    introduction_3 = TextField()
    introduction_4 = TextField()
    both_subject = TextField()
    is_deleted = IntegerField()

    class Meta:
        database = db  # This model uses the "spider" database.
        table_name = 'university_2_detail'  # 如果不指定，默认是person


    # 插入单条数据(返回新增id)
    def toInsert(self, row):
        try:
            return UniversityDetail.insert(row).execute()
        except Exception as e:
            return ''

    # 批量插入数据
    def toInsertBatch(self, rows):
        with db.atomic():
            UniversityDetail.insert_many(rows).execute()


    # 根据id，获取单条记录
    def getOne(self, id):
        try:
            return UniversityDetail.select().where(UniversityDetail.id == id).get()
        except Exception as e:
            return ''


    # 根据院校代码code，获取单条记录
    def getOneByCode(self, code):
        try:
            return UniversityDetail.select().where((UniversityDetail.code == code) & (UniversityDetail.year == 2023)).order_by(UniversityDetail.year.desc()).dicts().get()
        except Exception as e:
            return ''


    # 根据年份查询列表
    def getList(self, year):
        try:
            return UniversityDetail.select().where(UniversityDetail.year == year).dicts().execute()
        except Exception as e:
            print(e)
            return ''


    # 更新单条数据(返回影响记录数)
    def toUpdate(self, row):
        try:
            return UniversityDetail.update(
                name=row['name'], special_major=row['special_major'], change_rule=row['change_rule'],
                wan_plan=row['wan_plan'], introduction_1=row['introduction_1'], introduction_2=row['introduction_2'],
                introduction_3=row['introduction_3'], introduction_4=row['introduction_4'], both_subject=row['both_subject']
            ).where((UniversityDetail.year == row['year']) & (UniversityDetail.code == row['code'])).execute()
        except Exception as e:
            return ''


    # 更新单条数据(返回影响记录数)
    def toUpdate2(self, row):
        try:
            return UniversityDetail.update(
                change_rule=row['change_rule']).where(UniversityDetail.code == row['code']).execute()
        except Exception as e:
            return ''


if __name__ == '__main__':
    unversity = UniversityDetail()
    try:
        university_row = unversity.getOneByCode('10001')
        print(university_row)
    except Exception as e:
        print("except:", e)
